package com.bdqn.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.base.R;
import com.bdqn.pojo.GenConfig;
import com.bdqn.service.SysGeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 代码生成器
 *
 * @author lilibo
 * @date 2019/2/1
 */
@Api(value="代码生成器", tags="代码生成器接口")
@RestController
@RequestMapping("/generator")
public class SysGeneratorController {

	@Resource
	private SysGeneratorService sysGeneratorService;

	/**
	 * 分页查询数据库表
	 *
	 * @param tableName 参数集
	 * @return 数据库表
	 */
	@ApiOperation("分页查询数据库表")
	@GetMapping("/page")
	public R<IPage> list(Page page, String tableName) {
		return new R<>(sysGeneratorService.queryPage(page, tableName));
	}

	/**
	 * 生成代码
	 */
	@ApiOperation(value="生成代码", notes="生成代码（请下载压缩包文件）")
	@GetMapping("/code")
	@SneakyThrows
	public void gen(@ApiParam(value = "模块名称") @RequestParam(required=false, defaultValue="") String moduleName, @ApiParam(value = "表名") @RequestParam(required=false, defaultValue="") String tableName, HttpServletResponse response) {
		GenConfig genConfig = new GenConfig();
		genConfig.setModuleName(moduleName);
		genConfig.setTableName(tableName);

		byte[] data = sysGeneratorService.generatorCode(genConfig);

		response.reset();
		response.setHeader("Content-Disposition", String.format("attachment; filename=%s.zip", genConfig.getTableName()));
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
	}

}
